package org.seven.cpcrkapp.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import org.seven.cpcrkapp.R;
import org.seven.cpcrkapp.model.Result;
import org.seven.cpcrkapp.util.DialogUtils;
import org.seven.cpcrkapp.util.HttpUtils;

import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.EMDKManager.EMDKListener;
import com.symbol.emdk.EMDKManager.FEATURE_TYPE;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.ScanDataCollection.ScanData;
import com.symbol.emdk.barcode.Scanner.DataListener;
import com.symbol.emdk.barcode.Scanner.StatusListener;
import com.symbol.emdk.barcode.Scanner.TriggerType;
import com.symbol.emdk.barcode.StatusData.ScannerStates;
import com.symbol.emdk.barcode.StatusData;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FindActivity extends AppCompatActivity implements EMDKListener, DataListener, StatusListener {
    @BindView(R.id.toolbar_find)
    Toolbar toolbar;
    @BindView(R.id.textViewStatus)
    TextView textViewStatus;

    private EMDKManager emdkManager = null;
    private BarcodeManager barcodeManager = null;
    private Scanner scanner = null;
    private List<ScannerInfo> deviceList = new ArrayList<ScannerInfo>();
    private int scannerIndex = 0;
    private String statusString = "";
    private boolean bExtScannerDisconnected = false;

    @BindView(R.id.t_hjph)
    TextView t_hjph;
    @BindView(R.id.t_hjlh)
    TextView t_hjlh;
    @BindView(R.id.t_zl)
    TextView t_zl;
    @BindView(R.id.t_ks)
    TextView t_ks;
    @BindView(R.id.t_kqmc)
    TextView t_kqmc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
        if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
            updateStatus("扫描仪请求失败!");
        }
    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
        updateStatus("扫描仪请求成功!");
        this.emdkManager = emdkManager;
        initBarcodeManager();
        enumerateScannerDevices();
        initScanner();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (emdkManager != null) {
            initBarcodeManager();
            enumerateScannerDevices();
            initScanner();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        deInitScanner();
        deInitBarcodeManager();
    }

    @Override
    public void onClosed() {
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
        updateStatus("扫描仪意外关闭,请关闭并重新启动应用程序!");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
    }

    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
            ArrayList<ScanData> scanData = scanDataCollection.getScanData();
            for (ScanData data : scanData) {
                updateData(data.getData());
            }
        }
    }

    @Override
    public void onStatus(StatusData statusData) {
        ScannerStates state = statusData.getState();
        switch (state) {
            case IDLE:
                statusString = statusData.getFriendlyName() + "已启用...";
                updateStatus(statusString);
                scanner.triggerType = TriggerType.HARD;
                if (!scanner.isReadPending() && !bExtScannerDisconnected) {
                    try {
                        scanner.read();
                    } catch (ScannerException e) {
                        updateStatus(e.getMessage());
                    }
                }
                break;
            case WAITING:
                statusString = "扫描仪正在等待触发按钮...";
                updateStatus(statusString);
                break;
            case SCANNING:
                statusString = "扫描中...";
                updateStatus(statusString);
                break;
            case DISABLED:
                statusString = statusData.getFriendlyName() + "被禁用.";
                updateStatus(statusString);
                break;
            case ERROR:
                statusString = "发生了一个错误.";
                updateStatus(statusString);
                break;
            default:
                break;
        }
    }

    private void initScanner() {
        if (scanner == null) {
            if ((deviceList != null) && (deviceList.size() != 0)) {
                if (barcodeManager != null) {
                    scanner = barcodeManager.getDevice(deviceList.get(scannerIndex));
                }
            } else {
                updateStatus("无法获取指定的扫描仪设备,请关闭并重新启动应用程序!");
                return;
            }
            if (scanner != null) {
                scanner.addDataListener(this);
                scanner.addStatusListener(this);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    updateStatus(e.getMessage());
                    deInitScanner();
                }
            } else {
                updateStatus("无法初始化扫描仪设备!");
            }
        }
    }

    private void deInitScanner() {
        if (scanner != null) {
            try {
                scanner.disable();
                scanner.release();
            } catch (Exception e) {
                updateStatus(e.getMessage());
            }
            scanner = null;
        }
    }

    private void initBarcodeManager() {
        barcodeManager = (BarcodeManager) emdkManager.getInstance(FEATURE_TYPE.BARCODE);
    }

    private void deInitBarcodeManager() {
        if (emdkManager != null) {
            emdkManager.release(FEATURE_TYPE.BARCODE);
        }
    }


    private void enumerateScannerDevices() {
        if (barcodeManager != null) {
            deviceList = barcodeManager.getSupportedDevicesInfo();
        }
    }

    private void updateStatus(final String status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textViewStatus.setText(status);
            }
        });
    }

    private void updateData(final String data) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    final Result result = HttpUtils.postResult("/app/core/kccx", data);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Map<String, Object> map = (Map<String, Object>) result.get("kcxx");
                            t_hjph.setText((String) map.get("ggxh"));
                            t_hjlh.setText((String) map.get("cpbh") + '-' + (String) map.get("cpxh"));
                            t_zl.setText((String) map.get("zl"));
                            t_ks.setText((String) map.get("ks"));
                            t_kqmc.setText((String) map.get("kqmc"));
                        }
                    });
                } catch (Exception e) {
                    final String msg = e.getMessage();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            t_hjph.setText("");
                            t_hjlh.setText("");
                            t_zl.setText("");
                            t_ks.setText("");
                            t_kqmc.setText("");
                            DialogUtils.alert(msg);
                        }
                    });
                }
            }
        }).start();
    }
}
